/*

    tools23d - tools for converting images to 3D formats.
    Copyright (C) 2014  Dave Gorst

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <time.h>

#include "FreeImage.h"

#include "tools23d.h"
#include "util.h"

#ifdef BUILD_BTIME
	#include "btime23d.h"
	#include "cli-btime.h"
#else
	#include "photo23d.h"
	#include "cli-photo.h"
#endif

#include "cli-common.h"
#include "cli.h"
#include "image-fi.h"
#include "image.h"

#define ERROR_BUFFER_LENGTH 509

/* NOTE : Caution - check nothing can overflow this ... */

static char last_error [ERROR_BUFFER_LENGTH];
static BOOL error_has_occurred;

/**
Set the last error text.

@param	errortext	Printf-style formatted text giving error details.
*/

void T3D_SetLastError (char * errortext, ...)
{
	va_list args;

	va_start (args, errortext);

	(void) vsnprintf (last_error, ERROR_BUFFER_LENGTH-1, errortext, args);

	va_end (args);

	error_has_occurred = TRUE;
}

/**
Retrieve the last error text.

@return	Printf-style formatted text giving error details.
*/

char * T3D_ReadLastError (void)
{
	return &last_error [0];
}


/**
Check if an error has occurred.

@return	::TRUE if an error has occurred. Otherwise ::FALSE.
*/

BOOL T3D_CheckForError (void)
{
	return (BOOL) error_has_occurred;
}

/**
Main entry point of our code.

@return	::TRUE if an error has occurred. Otherwise ::FALSE.
*/

int main(int argc, char * argv[])
{
	params my_params;
	int result = 0;

	error_has_occurred = FALSE;
	T3D_InitialiseUI (&my_params);

	if ((result = T3D_ProcessCommandline (argc, argv, &my_params)) == t3d_success)
	{
		
		T3D_InitialiseBackend ();

		result = T3D_Run (&my_params);

		if (T3D_CheckForError())
			T3D_OutputError ("%s\n\n", T3D_ReadLastError());

		T3D_ShutdownBackend ();
	}

	T3D_ShutdownUI (&my_params);

	return result;
}
